<script>
import UniNavBar from "../../uni_modules/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue";
import UniIcons from "../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import { mapState } from 'vuex';
import { queryHealthHistoryByType } from "../../api/metrices";

// 状态判断逻辑，与 healthObserve.vue 保持一致
const STATUS_HANDLERS = {
  '体重': (val) => {
    if (val > 90) return '偏高';
    if (val < 50) return '偏低';
    return '正常';
  },
  '血糖': (val, type) => {
    if (type === '餐前') {
      if (val > 6.1) return '偏高';
      if (val < 3.9) return '偏低';
    }
    // 可以为其他类型（如餐后）添加更多逻辑
    return '正常';
  },
  '血压': (systolic, diastolic) => {
    if (systolic >= 140 || diastolic >= 90) return '偏高';
    if (systolic < 90 || diastolic < 60) return '偏低';
    return '正常';
  },
  '心率': (val) => {
    if (val > 100) return '偏高';
    if (val < 60) return '偏低';
    return '正常';
  }
};

export default {
  name: "health-history",
  components: { UniNavBar, UniIcons },
  data() {
    return {
      dataType: '', // 动态设置
      latestData: { // 初始化为空
        value: '--',
        unit: '',
        status: '正常',
        time: '暂无数据'
      },
      historyList: [] // 初始化为空数组
    };
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    }),
    pageTitle() {
      return `${this.dataType}历史记录`;
    }
  },
  onLoad(options) {
    if (options.type) {
      this.dataType = options.type;
      this.fetchData(options.type);
    }
  },
  methods: {
    async fetchData(type) {
      try {
        const { data: response } = await queryHealthHistoryByType(this.user.residentId, type);
        if (response.code === 200 && response.data && response.data.length > 0) {
          const history = response.data;
          this.historyList = this.transformHistory(history, type);
          
          // 设置最新数据
          const latest = history[0]; // 后端返回的是按时间倒序的
          this.updateLatestData(latest, type);

        } else {
          this.historyList = []; // 清空旧数据
          uni.showToast({ title: response.msg || '暂无历史数据', icon: 'none' });
        }
      } catch (error) {
        console.error("获取历史数据失败:", error);
        uni.showToast({ title: '网络错误，请稍后再试', icon: 'none' });
      }
    },
    
    // 更新顶部最新数据卡片
    updateLatestData(latest, type) {
      const handlers = {
        '体重': () => {
          this.latestData.value = latest.weightValue;
          this.latestData.unit = 'Kg';
          this.latestData.status = STATUS_HANDLERS['体重'](latest.weightValue);
        },
        '血糖': () => {
          this.latestData.value = latest.glucoseValue;
          this.latestData.unit = 'mmol/L';
          this.latestData.status = STATUS_HANDLERS['血糖'](latest.glucoseValue, latest.measurementType);
        },
        '血压': () => {
          this.latestData.value = `${latest.systolicPressure}/${latest.diastolicPressure}`;
          this.latestData.unit = 'mmHg';
          this.latestData.status = STATUS_HANDLERS['血压'](latest.systolicPressure, latest.diastolicPressure);
        },
        '心率': () => {
          this.latestData.value = latest.heartRate;
          this.latestData.unit = 'bpm';
          this.latestData.status = STATUS_HANDLERS['心率'](latest.heartRate);
        }
      };
      if (handlers[type]) {
        handlers[type]();
        this.latestData.time = this.formatDateTime(latest.measurementDate).full;
      }
    },

    // 将从后端获取的原始历史数据转换为前端需要的格式
    transformHistory(history, type) {
      return history.map(item => {
        const { date, time } = this.formatDateTime(item.measurementDate);
        const common = { id: item.recordId, date, time };
        
        const transformers = {
          '体重': () => ({
            ...common,
            value: item.weightValue,
            status: STATUS_HANDLERS['体重'](item.weightValue)
          }),
          '血糖': () => ({
            ...common,
            value: item.glucoseValue,
            status: STATUS_HANDLERS['血糖'](item.glucoseValue, item.measurementType)
          }),
          '血压': () => ({
            ...common,
            value: `${item.systolicPressure}/${item.diastolicPressure}`,
            status: STATUS_HANDLERS['血压'](item.systolicPressure, item.diastolicPressure)
          }),
          '心率': () => ({
            ...common,
            value: item.heartRate,
            status: STATUS_HANDLERS['心率'](item.heartRate)
          })
        };
        
        return transformers[type] ? transformers[type]() : {};
      });
    },

    // 格式化日期时间
    formatDateTime(dateTimeString) {
      if (!dateTimeString) return { date: '', time: '', full: '' };
      const [datePart, timePart] = dateTimeString.replace('T', ' ').split(' ');
      return {
        date: datePart,
        time: timePart ? timePart.substring(0, 5) : '', // 只取 HH:mm
        full: dateTimeString.replace('T', ' ')
      };
    },

    addNewRecord() {
      uni.showToast({ title: `新增${this.dataType}记录`, icon: 'none' });
    },
    editRecord(item) {
      uni.showToast({ title: `编辑ID为 ${item.id} 的记录`, icon: 'none' });
    },
    deleteRecord(item) {
      uni.showModal({
        title: '提示',
        content: `确定要删除这条${this.dataType}记录吗？`,
        success: (res) => {
          if (res.confirm) {
            // 此处应调用API删除
            this.historyList = this.historyList.filter(i => i.id !== item.id);
            uni.showToast({ title: '删除成功', icon: 'success' });
          }
        }
      });
    }
  }
}
</script>

<template>
  <view class="page-container">
    <!-- 最新数据总览卡片 -->
    <view class="latest-data-card">
      <view class="latest-value-area">
        <text class="value">{{ latestData.value }}</text>
        <text class="unit">{{ latestData.unit }}</text>
      </view>
      <view class="latest-info-area">
        <view class="status-tag" :class="[latestData.status === '偏高' ? 'high' : 'normal']">
          {{ latestData.status }}
        </view>
        <text class="time">最近测量：{{ latestData.time }}</text>
      </view>
    </view>

    <!-- 历史记录列表 -->
    <view class="history-container">
      <view class="section-title">{{ this.pageTitle }}</view>
      <view class="history-list">
        <view v-if="historyList.length === 0" class="empty-list">
          <text>暂无记录</text>
        </view>
        <view class="history-item" v-for="item in historyList" :key="item.id">
          <view class="item-left">
            <text class="item-date">{{ item.date }}</text>
            <text class="item-time">{{ item.time }}</text>
          </view>
          <view class="item-middle">
            <text class="item-value" :class="{ 'high-value': item.status === '偏高' }">
              {{ item.value }}
            </text>
            <text class="item-status" :class="{ 'high-value': item.status === '偏高' }">
              {{ item.status }}
            </text>
          </view>
          <view class="item-right">
            <text class="action-btn edit" @click="editRecord(item)">编辑</text>
            <text class="action-btn delete" @click="deleteRecord(item)">删除</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 悬浮新增按钮 -->
    <view class="fab-btn" @click="addNewRecord">
      <uni-icons type="plusempty" size="24" color="#fff"></uni-icons>
    </view>

  </view>
</template>

<style scoped>
/* 全局页面样式 */
.page-container {
  background-color: #f5f8ff;
  min-height: 100vh;
  padding-bottom: 40rpx;
}

/* 最新数据卡片 */
.latest-data-card {
  background: linear-gradient(135deg, #ff7e5f, #feb47b); /* 血糖主题色，您可以根据不同数据类型更换 */
  color: white;
  border-radius: 24rpx;
  padding: 40rpx;
  margin: 24rpx 30rpx;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8rpx 20rpx rgba(254, 180, 123, 0.4);
}
.latest-value-area {
  display: flex;
  align-items: baseline;
}
.value {
  font-size: 80rpx;
  font-weight: bold;
}
.unit {
  font-size: 32rpx;
  margin-left: 10rpx;
}
.latest-info-area {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 16rpx;
  opacity: 0.9;
}
.status-tag {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  background-color: rgba(255, 255, 255, 0.3);
}
.time {
  font-size: 24rpx;
}
.status-tag.high {
  /* 可以在这里为不同状态定义不同样式 */
}


/* 区块标题 */
.section-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  padding: 0 30rpx;
  margin-top: 40rpx;
  margin-bottom: 24rpx;
}

/* 图表容器 */
.chart-container {
}
.chart-placeholder {
  height: 300rpx;
  background-color: #ffffff;
  margin: 0 30rpx;
  border-radius: 16rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #aaa;
}

/* 历史记录 */
.history-container {
}
.history-list {
  margin: 0 30rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 0 30rpx;
}
.history-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}
.history-item:last-child {
  border-bottom: none;
}
.item-left {
  display: flex;
  flex-direction: column;
  width: 180rpx;
}
.item-date {
  font-size: 28rpx;
  color: #333;
}
.item-time {
  font-size: 24rpx;
  color: #999;
}
.item-middle {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.item-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}
.item-status {
  font-size: 24rpx;
  color: #666;
}
/* 异常数据标红 */
.high-value {
  color: #fa5151;
}

.item-right {
  display: flex;
  gap: 24rpx;
}
.action-btn {
  font-size: 26rpx;
  color: #007aff;
}
.action-btn.delete {
  color: #fa5151;
}
.empty-list {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
}


/* 悬浮新增按钮 */
.fab-btn {
  position: fixed;
  right: 40rpx;
  bottom: 100rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #007aff;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 8rpx 20rpx rgba(0, 122, 255, 0.4);
}
</style>

